﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Xml;
using ONNONLed5KSDKD;
using System.Threading;
using CCWin;

namespace 智能仓库系统
{
    public partial class Form1 : Skin_Mac
    {
        public int type;
        uint[] Hand_Buf = new uint[12];     //存放12个屏幕的IP连接句柄
        int Car_Count = 11;     //板卡数量，有一块没有接，接上后改为12
        string iniFilePath = "";    //ini存放目录
        string[] BarcodePortName = new string[6];   //存放6个扫码枪的串口号   
        string[] BarcodeBaudRate = new string[6];   //存放6个串口的波特率
        bool MessageShow_OK = true;  //成功报警消息
        bool MessageShow_NG = false;  //错误报警消息
        uint m_dwCurHand;   //返回连接的句柄
        uint timeout = 2;    //通信超时时间
        bool utf8_flag = false;     //客户电脑采用utf8编码 true为客户电脑
        string defaultPWD;
        int timer1_time;
        Led5kSDK.bx_5k_area_header bx_5k;   
        byte[] AreaText;

        //string[] SerialDataReceived = new string[6];    //缓存扫描枪数据，用来对比和上次是否重复

        Serial serial = new Serial();
        List<SerialPort> Serial_List = new List<SerialPort>(6);

        string[] PierBuf = new string[10] { "暂无车辆", "暂无车辆" , "暂无车辆" , "暂无车辆" , "暂无车辆",
        "暂无车辆","暂无车辆","暂无车辆","暂无车辆","暂无车辆"};    //存放10个码头对应的车牌号


        string[] IP_Buf = new string[12] { "10.93.148.241","10.93.148.242","10.93.148.243","10.93.148.244",
                                            "10.93.148.245","10.93.148.246","10.93.148.247","10.93.148.248",
                                            "10.93.148.249","10.93.148.250","10.93.148.252","10.93.148.251" };   //存放12个屏幕的IP

        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            //textBox12.Text = names[0];
            ONNONLed5KSDKD.Led5kSDK.InitSdk(2, 2);
        }

        //更新任一屏幕的动态数据
        /// <summary>
        /// 
        /// </summary>
        /// <param name="StayTime">停留时间</param>
        /// <param name="DisplayMode">显示特技 1   静止显示2   快速打出3   向左移动4   向右移动5   向上移动6   向下移动</param>
        /// <param name="RunMode">显示模式 0  自动循环显示 1  完成后停留在最后一页 2  超时未完成删除该信息</param>
        /// <param name="i">动态编号</param>
        /// <param name="X"></param>
        /// <param name="Y"></param>
        /// <param name="Width"></param>
        /// <param name="Height"></param>
        /// <param name="data"></param>
        public int  UpdateArea(byte StayTime, byte DisplayMode, byte RunMode, uint i, short X, short Y, short Width, short Height, string data)
        {
            int x = 10;
            bx_5k.DynamicAreaLoc = (byte)i;     //动态编号
            Led5K_Set(StayTime, DisplayMode, RunMode, X, Y, Width, Height, data);   //设置屏幕的参数，起始位置大小，数据
            try
            {
                x = ONNONLed5KSDKD.Led5kSDK.SCREEN_SendDynamicArea(m_dwCurHand, bx_5k, (ushort)bx_5k.DataLen, AreaText);
            }
            catch
            {

            }
            return x;
        }

        //停留时间0 向左移动 完成后停留在最后一页 
        //多行显示 自动换行
        public int UpdateArea(uint i, short X, short Y, short Width, short Height, string data)
        {
            int x = 10;
            bx_5k.DynamicAreaLoc = (byte)i;     //动态编号
            Led5K_Set(0, 5, 1, X, Y, Width, Height, data);   //设置屏幕的参数，起始位置大小，数据
            bx_5k.SingleLine = 2;   //多行显示
            bx_5k.NewLine = 2;      //自动换行
            try
            {
                x = ONNONLed5KSDKD.Led5kSDK.SCREEN_SendDynamicArea(m_dwCurHand, bx_5k, (ushort)bx_5k.DataLen, AreaText);
            }
            catch
            {

            }
            return x;
        }    

        //设置屏幕显示参数
        /// <summary>
        /// 
        /// </summary>
        /// <param name="StayTime">停留时间</param>
        /// <param name="DisplayMode">显示特技 1   静止显示2   快速打出3   向左移动4   向右移动5   向上移动6   向下移动</param>
        /// <param name="RunMode">显示模式 0  自动循环显示 1  完成后停留在最后一页 2  超时未完成删除该信息</param>
        /// <param name="X"></param>
        /// <param name="Y"></param>
        /// <param name="Width"></param>
        /// <param name="Height"></param>
        /// <param name="data"></param>
        private void Led5K_Set(byte StayTime, byte DisplayMode, byte RunMode, short X, short Y, short Width, short Height, string data)
        {
            /*
             * 设置起始坐标和区域大小、行间距
             */
            bx_5k.AreaType = 0x06;
            bx_5k.AreaX = X;
            bx_5k.AreaX /= 8;
            bx_5k.AreaY = Y;
            bx_5k.AreaWidth = Width;
            bx_5k.AreaWidth /= 8;
            bx_5k.AreaHeight = Height;

            bx_5k.Lines_sizes = 0;  //行间距

            /*
             运行模式
             0  自动循环显示
             1  完成后停留在最后一页
             2  超时未完成删除该信息
             */
            bx_5k.RunMode = RunMode;

            /*
             超时时间
             */
            bx_5k.Timeout = 0;


            bx_5k.Reserved1 = 0;
            bx_5k.Reserved2 = 0;
            bx_5k.Reserved3 = 0;

            /*
             是否单行
             1  单行显示
             2  多行显示
             */
            bx_5k.SingleLine = 1;

            /*
             是否自动换行
             1  手动换行
             2  自动换行
             */
            bx_5k.NewLine = 1;

            /*
             显示特技
             1   静止显示
             2   快速打出
             3   向左移动
             4   向右移动
             5   向上移动
             6   向下移动
             */
            bx_5k.DisplayMode = DisplayMode;

            bx_5k.ExitMode = 0x00;

            /*
             运行速度
             */
            bx_5k.Speed = 8;

            /*
             停留时间
             */
            bx_5k.StayTime = StayTime;

            Encoding ec = Encoding.GetEncoding("gb2312");
            AreaText = ec.GetBytes(data.Trim());

            //AreaText = System.Text.Encoding.Default.GetBytes(data.Trim());
            bx_5k.DataLen = AreaText.Length;
        }

        //设置连接IP，端口为5005，返回连接句柄,板卡型号5K1Q-YY 对应0x5c
        private uint Set_data(string IP)
        {
            byte[] led_ip = System.Text.Encoding.ASCII.GetBytes(IP);
            uint led_port = Convert.ToUInt32("5005");
            uint hand = ONNONLed5KSDKD.Led5kSDK.CreateClient(led_ip, led_port, (Led5kSDK.bx_5k_card_type)0x5c, 1, null);
            return hand;
        }

        //显示所有屏幕内容
        private void Show_ALL()
        {
            button6.Enabled = false;
            for (int i = 0; i < 10; i++)
            {
                m_dwCurHand = Set_data(IP_Buf[i]);    //连接对应屏幕的IP
                ONNONLed5KSDKD.Led5kSDK.SetTimeout(m_dwCurHand, timeout);   //设置超时时间
                Thread.Sleep(1000);
                ONNONLed5KSDKD.Led5kSDK.SCREEN_DelDynamicArea(m_dwCurHand, 255);    //删除所有动态

                if (m_dwCurHand != 0)   //连接成功
                {
                    int x = UpdateArea(0, 1, 0, 0, 208, 0, 176, 24, "成品" + (i + 6).ToString("00") + "码位 | " + PierBuf[i]);
                    Thread.Sleep(1000);
                    x = UpdateArea(0, 1, 0, 1, 16, 0, 176, 24, "成品" + (i + 6).ToString("00") + "码位 | " + PierBuf[i]);
                    Thread.Sleep(1000);
                    ONNONLed5KSDKD.Led5kSDK.SCREEN_SetBrightness(m_dwCurHand, 1, 5, null);
                    Sound_Play((i + 6).ToString() + "号码头声音测试");
                }
                else
                {
                    WriteLog("errlog", "连接控制器失败");
                    if (MessageShow_NG == true)
                       MessageBox.Show("连接控制器失败");
                }
                Thread.Sleep(3000);
                ONNONLed5KSDKD.Led5kSDK.Destroy(m_dwCurHand);
            }
            MessageBox.Show("显示完成");
            button6.Enabled = true;
        }

        /// <summary>
        /// 修改单个屏幕内容车牌号
        /// </summary>
        /// <param name="num">车牌</param>
        private void Modify_LicPlate(uint num)
        {
            m_dwCurHand = Set_data(IP_Buf[num]);    //连接对应屏幕的IP
            ONNONLed5KSDKD.Led5kSDK.SetTimeout(m_dwCurHand, timeout);
            if (m_dwCurHand != 0)   //连接成功
            {
                int x = UpdateArea(0, 1, 0, 0, 208, 0, 176, 24, "成品" + (num + 6).ToString("00") + "码位 | " + PierBuf[num]);
                Thread.Sleep(100);
                x = UpdateArea(0, 1, 0, 1, 16, 0, 176, 24, "成品" + (num + 6).ToString("00") + "码位 | " + PierBuf[num]);
                ONNONLed5KSDKD.Led5kSDK.SCREEN_SetBrightness(m_dwCurHand, 1, 5, null);
            }
            else
            {
                WriteLog("errlog", "连接控制器失败");
                if (MessageShow_NG == true)
                    MessageBox.Show("连接控制器失败");
            }

            ONNONLed5KSDKD.Led5kSDK.Destroy(m_dwCurHand);           
        }

        //删除某个屏幕所有动态
        private void delete_dynamic(uint num)
        {
            m_dwCurHand = Set_data(IP_Buf[num]);    //连接对应屏幕的IP
            ONNONLed5KSDKD.Led5kSDK.SetTimeout(m_dwCurHand, timeout);
            if (m_dwCurHand != 0)   //连接成功
            {
                ONNONLed5KSDKD.Led5kSDK.SCREEN_DelDynamicArea(m_dwCurHand, 255);
            }
            else
            {
                WriteLog("errlog", "连接控制器失败");
                if (MessageShow_NG == true)
                    MessageBox.Show("连接控制器失败");
            }
            ONNONLed5KSDKD.Led5kSDK.Destroy(m_dwCurHand);
        }

        //修改单个屏幕DN和栈板信息，播放声音
        //num:表示12块屏幕
        //DN:存放DN号的数组
        //Pallet:存放栈板的数组
        private void Modify_DN(uint num ,string[] DN,string[] Pallet,int length)
        {
            string showData = null;
            string soundData = null;

            for (int i = 0; i < length; i++)
            {
                showData += "DN:" + DN[i] + "栈板:" + Pallet[i];
                showData += " ";
            }

            for (int i = 0; i < length; i++)
            {
                soundData += "DN:" + DN[i] + "栈板:" + Pallet[i].Insert(1, " ");
                soundData += " ";
            }


            soundData += " 成品";
            showData += " 成品";

            m_dwCurHand = Set_data(IP_Buf[num]);    //连接对应屏幕的IP
            if (m_dwCurHand != 0)   //连接成功
            {
                UpdateArea(0, 3, 2, 2, 0, 24, 192, 24, showData + (num + 6).ToString("00") + "码位装柜中...");
                Thread.Sleep(100);
                UpdateArea(0, 3, 2, 3, 192, 24, 192, 24, showData + (num + 6).ToString("00") + "码位装柜中...");
                soundData = soundData + (num + 6).ToString("00") + "码位装柜中...";

                Sound_Play(soundData);
            }
            else
            {
                WriteLog("errlog", "连接控制器失败");
                if (MessageShow_NG == true)
                    MessageBox.Show("连接控制器失败");
            }
                     
            ONNONLed5KSDKD.Led5kSDK.Destroy(m_dwCurHand);
        }

        //任意屏幕播放声音
        private void Sound_Play(string Sound)
        {
            byte[] SoundAreaText;
            SoundAreaText = System.Text.Encoding.Default.GetBytes(Sound.Trim());
   
            int x = ONNONLed5KSDKD.Led5kSDK.SCREEN_SendSoundDynamicArea(m_dwCurHand, bx_5k, (ushort)bx_5k.DataLen,
                    AreaText, 2, 0, 10, 4, SoundAreaText.Length, SoundAreaText);
        }

        //错误内容
        private void Update_Internal_Screen(string num, string str)
        {
            if (num == "L")     //内部左边屏幕
            {
                m_dwCurHand = Set_data(IP_Buf[11]);    //连接对应屏幕的IP
            }
            else if (num == "R")    //内部右边屏幕
            {
                m_dwCurHand = Set_data(IP_Buf[10]);    //连接对应屏幕的IP
            }

            ONNONLed5KSDKD.Led5kSDK.SetTimeout(m_dwCurHand, timeout);
            if (m_dwCurHand != 0)   //连接成功
            {
                //ONNONLed5KSDKD.Led5kSDK.SCREEN_DelDynamicArea(m_dwCurHand, 255);
                //Thread.Sleep(500);
                //UpdateArea(0, 0, 0, 64, 48, str);
                Sound_Play(str);
                Thread.Sleep(10000);

                UpdateArea(0, 1, 0, 0, 0, 0, 64, 24, "成品自动");
                Thread.Sleep(100);
                UpdateArea(0, 1, 0, 1, 0, 24, 64, 24, "装柜系统");
            }
            else
            {
                WriteLog("errlog", "连接控制器失败");
                if (MessageShow_NG == true)
                    MessageBox.Show("连接控制器失败");
            }

            ONNONLed5KSDKD.Led5kSDK.Destroy(m_dwCurHand);
        }

        //正确内容
        private void Update_Internal_Screen(string num, string Pier, string[] Pallet, int length)
        {
            string showData = null;
            string soundData = null;
            bx_5k.DisplayMode = 3;  //向左移动
            for (int i = 0; i < length; i++)
            {
                showData += "栈板:" + Pallet[i];
                showData += " ";
            }
            for (int i = 0; i < length; i++)
            {
                soundData += "栈板:" + Pallet[i].Insert(1, " ");
                soundData += " ";
            }

            if (num == "L")     //内部左边屏幕
            {
                m_dwCurHand = Set_data(IP_Buf[11]);    //连接对应屏幕的IP
            }
            else if (num == "R")    //内部右边屏幕
            {
                m_dwCurHand = Set_data(IP_Buf[10]);    //连接对应屏幕的IP
            }

            ONNONLed5KSDKD.Led5kSDK.SetTimeout(m_dwCurHand, timeout);
            if (m_dwCurHand != 0)   //连接成功
            {
                UpdateArea(0, 3, 1, 0, 0, 0, 64, 24, showData);
                Thread.Sleep(100);
                UpdateArea(0, 3, 1, 1, 0, 24, 64, 24, "请送至成品" + Pier + "码位");
                //Sound_Play(soundData + "请送至成品" + Pier + "码位");
                Sound_Play("成品" + Pier + "码位" + soundData + "装货");
                for (int i = 0; i < length; i++)
                {
                    Thread.Sleep(8000);
                }
                UpdateArea(0, 1, 0, 0, 0, 0, 64, 24, "成品自动");
                Thread.Sleep(100);
                UpdateArea(0, 1, 0, 1, 0, 24, 64, 24, "装柜系统");
            }
            else
            {
                WriteLog("errlog", "连接控制器失败");
                if (MessageShow_NG == true)
                    MessageBox.Show("连接控制器失败");
            }

            ONNONLed5KSDKD.Led5kSDK.Destroy(m_dwCurHand);
        }


        private bool Connect_All()
        {
            string err = null;
            bool Connect_Flag = true;  //12个板卡都连接成功后返回true

            for (int i = 0; i < Car_Count; i++)
            {
                Hand_Buf[i] = Set_data(IP_Buf[i]);
                ONNONLed5KSDKD.Led5kSDK.SetTimeout(Hand_Buf[i], timeout);
                if (Hand_Buf[i] == 0)
                {
                    err += (i + 6).ToString();        //记录没有连接成功的板卡
                    err += ",";
                    Connect_Flag = false;
                }
            }
            if (Connect_Flag == false)
            {
                if (MessageShow_NG == true)
                    MessageBox.Show(err + "号板卡连接失败");
            }
            else
            {
                //if (MessageShow_OK == true)
                    MessageBox.Show("所有板卡连接成功");
            }
            return Connect_Flag;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Connect_All();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            //Delect_All();
            button6.Enabled = false;
            for (uint i = 0; i < 10; i++)
            {
                delete_dynamic(i);
                Thread.Sleep(500);
                Modify_LicPlate(i);
                Thread.Sleep(1000);
            }
            MessageBox.Show("显示完成");
            button6.Enabled = true;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 11; i++)
            {
                m_dwCurHand = Set_data(IP_Buf[i]);    //连接对应屏幕的IP
                ONNONLed5KSDKD.Led5kSDK.SetTimeout(m_dwCurHand, timeout);   //设置超时时间
                //ONNONLed5KSDKD.Led5kSDK.SCREEN_DelDynamicArea(m_dwCurHand, 255);    //删除所有动态

                if (m_dwCurHand != 0)   //连接成功
                {
                    
                }
                else
                {
                    WriteLog("errlog", "连接控制器失败");
                    if (MessageShow_NG == true)
                        MessageBox.Show("连接控制器失败");
                }
                Thread.Sleep(500);
                ONNONLed5KSDKD.Led5kSDK.Destroy(m_dwCurHand);
            }
            

            for (int i = 0; i < 10; i++)
            {
                m_dwCurHand = Set_data(IP_Buf[i]);    //连接对应屏幕的IP
                ONNONLed5KSDKD.Led5kSDK.SetTimeout(m_dwCurHand, timeout);   //设置超时时间
                //ONNONLed5KSDKD.Led5kSDK.SCREEN_DelDynamicArea(m_dwCurHand, 255);    //删除所有动态

                if (m_dwCurHand != 0)   //连接成功
                {
                    ONNONLed5KSDKD.Led5kSDK.SCREEN_ForceOnOff(m_dwCurHand, 1);
                    
                }
                else
                {
                    WriteLog("errlog", "连接控制器失败");
                    if (MessageShow_NG == true)
                        MessageBox.Show("连接控制器失败");
                }
                Thread.Sleep(2000);
                ONNONLed5KSDKD.Led5kSDK.Destroy(m_dwCurHand);
            }
            MessageBox.Show("开机完成");
        }

        private void button9_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 11; i++)
            {
                m_dwCurHand = Set_data(IP_Buf[i]);    //连接对应屏幕的IP
                ONNONLed5KSDKD.Led5kSDK.SetTimeout(m_dwCurHand, timeout);   //设置超时时间
                //ONNONLed5KSDKD.Led5kSDK.SCREEN_DelDynamicArea(m_dwCurHand, 255);    //删除所有动态

                if (m_dwCurHand != 0)   //连接成功
                {
                    int err = ONNONLed5KSDKD.Led5kSDK.SCREEN_ForceOnOff(m_dwCurHand, 2);
                }
                else
                {
                    WriteLog("errlog", "连接控制器失败");
                    if (MessageShow_NG == true)
                        MessageBox.Show("连接控制器失败");
                }
                Thread.Sleep(500);
                ONNONLed5KSDKD.Led5kSDK.Destroy(m_dwCurHand);
            }
            MessageBox.Show("关机完成");
        }


        private void Delect_All()
        {
            for (int i = 0; i < Car_Count; i++)
            {
                try
                {
                    ONNONLed5KSDKD.Led5kSDK.SCREEN_DelDynamicArea(Hand_Buf[i], 255);
                }
                catch
                {
                    
                }
                Thread.Sleep(1000);
            }
            if (MessageShow_OK == true)
                MessageBox.Show("删除成功！");
        }

        private void button10_Click(object sender, EventArgs e)
        {
            Delect_All();
        }

       
        private void saveIniFile()
        {           
            if (!File.Exists(this.iniFilePath))
            {
                using (File.Create(this.iniFilePath)) { };
            }
            for (int i = 0; i < 6; i++)
            {
                IniFileHelper.SetValue("扫描枪", "扫码枪" + (i + 1).ToString() + "号", "", this.iniFilePath);
            }
            IniFileHelper.SetValue("报警信息", "启用", "是", this.iniFilePath);
            if (MessageShow_OK == true)
                MessageBox.Show("存储成功");
        }

        private void readIniFile()
        {
            if (File.Exists(this.iniFilePath))
            {               
                for (int i = 0; i < 6; i++)
                {
                    BarcodePortName[i] = IniFileHelper.GetValue("BarcodeCOM", "Barcode" + (i + 1).ToString(), this.iniFilePath);
                    BarcodeBaudRate[i] = IniFileHelper.GetValue("BaudRate", "BaudRate" + (i + 1).ToString(), this.iniFilePath);

                    if (BarcodePortName[i].Contains("COM"))
                    {
                        Serial_List[i].PortName = BarcodePortName[i];
                        Serial_List[i].BaudRate = int.Parse(BarcodeBaudRate[i]);
                        try
                        {
                            Serial_List[i].Open();
                        }
                        catch
                        {
                            MessageBox.Show(Serial_List[i].PortName + "串口打开错误");
                        }
                    }
                }


                if (IniFileHelper.GetValue("BarcodeCOM", "STM32", this.iniFilePath).Contains("COM"))
                {
                    serialPort1.PortName = IniFileHelper.GetValue("BarcodeCOM", "STM32", this.iniFilePath);
                    try
                    {
                        serialPort1.Open();
                    }
                    catch
                    {
                        MessageBox.Show(serialPort1.PortName + "串口打开错误");
                    }
                }

                if (IniFileHelper.GetValue("Alarm", "OKAlarm", this.iniFilePath) == "true")
                {
                    MessageShow_OK = true;
                }
                else
                {
                    MessageShow_OK = false;
                }

                if (IniFileHelper.GetValue("Alarm", "NGAlarm", this.iniFilePath) == "true")
                {
                    MessageShow_NG = true;
                }
                else
                {
                    MessageShow_NG = false;
                }

                if (IniFileHelper.GetValue("Language", "Language", this.iniFilePath) == "UTF8")
                {
                    utf8_flag = true;
                }
                else
                {
                    utf8_flag = false;
                }


                if (IniFileHelper.GetValue("SET", "pwd", this.iniFilePath) != null)
                {
                    defaultPWD = IniFileHelper.GetValue("SET", "pwd", this.iniFilePath);
                }

                if (MessageShow_OK == true)
                    MessageBox.Show("读取文档成功");
            }
            else
            {
                if (MessageShow_NG == true)
                    MessageBox.Show("文件加载失败，请确认是否存在此文件：" + this.iniFilePath);
            }
        }

        private void Serial_List_Add()
        {
            Serial_List.Add(serial.serialPort1);
            Serial_List.Add(serial.serialPort2);
            Serial_List.Add(serial.serialPort3);
            Serial_List.Add(serial.serialPort4);
            Serial_List.Add(serial.serialPort5);
            Serial_List.Add(serial.serialPort6);
        } 

        private void Form1_Load(object sender, EventArgs e)
        {
            Serial_List_Add();      //添加list成员
            serial.Serial_Init();   //初始化所有串口
            string directory = System.AppDomain.CurrentDomain.BaseDirectory;
            this.iniFilePath = Path.Combine(directory, "config.ini");
            //saveIniFile();
            readIniFile();

            //bool con_flag;
            //con_flag = Connect_All();      //连接所有板卡
            try
            {
                serialPort_Sys.Encoding = System.Text.Encoding.GetEncoding("gb2312");     //设置串口接收到的字符串的编码
                serialPort_Sys.Open();
            }
            catch
            {
                if (MessageShow_NG == true)
                    MessageBox.Show("串口打开错误！");
            }
        }

        private void button12_Click(object sender, EventArgs e)
        {
            Modify_LicPlate((uint)numericUpDown1.Value - 6);                 
        }

        private void button3_Click(object sender, EventArgs e)
        {
            m_dwCurHand = Set_data(IP_Buf[(uint)numericUpDown1.Value - 6]);    //连接对应屏幕的IP
            ONNONLed5KSDKD.Led5kSDK.SetTimeout(m_dwCurHand, timeout);
            if (m_dwCurHand != 0)   //连接成功
            {
                Sound_Play(numericUpDown1.Value.ToString() + "号码头声音测试");
            }
            else
            {
                WriteLog("errlog", "连接控制器失败");
                if (MessageShow_NG == true)
                    MessageBox.Show("连接控制器失败");
            }

            ONNONLed5KSDKD.Led5kSDK.Destroy(m_dwCurHand);
        }

        public void WriteLog(string documentName, string msg)
        {
            string errorLogFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log");
            if (!System.IO.Directory.Exists(errorLogFilePath))
            {
                System.IO.Directory.CreateDirectory(errorLogFilePath);
            }
            string logFile = System.IO.Path.Combine(errorLogFilePath, documentName + "@" + DateTime.Today.ToString("yyyy-MM-dd") + ".txt");
            bool writeBaseInfo = System.IO.File.Exists(logFile);
            StreamWriter swLogFile = new StreamWriter(logFile, true, Encoding.Unicode);
            swLogFile.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "\t" + msg);
            swLogFile.Close();
            swLogFile.Dispose();
        }

        /*
         * 接收IT系统后数据处理部分
         */
        List<byte> buffer = new List<byte>(4096);
        byte[] ReceiveBytes = new byte[100];    

        private void serialPort_Sys_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string[] DN = new string[10];   //存放一次接收的DN号
            string[] Pallet = new string[10];   //存放一次接收的栈板号

            string str = serialPort_Sys.ReadTo("\n");

            if (utf8_flag == true)  //重新编码
            {
                byte[] strByte = Encoding.Default.GetBytes(str);

                //需要转成了编码
                Encoding ecLastCode = Encoding.GetEncoding("utf-8");
                WriteLog("serialdata", ecLastCode.GetString(strByte));
            }

            //byte[] strByte1 = Encoding.GetEncoding("").GetBytes(str);
            //接收到下发的车牌号
            if (str.Contains("999"))
            {
                try
                {
                    str = str.Replace(",999", "");
                    str = str.Replace("666,", "");
                    str = str.Trim();
                    if (utf8_flag == true)  //重新编码
                    {
                        byte[] strByte = Encoding.Default.GetBytes(str);

                        //需要转成了编码
                        Encoding ecLastCode = Encoding.GetEncoding("utf-8");
                        str = ecLastCode.GetString(strByte);
                    }

                    textBox5.AppendText(str + "\r\n");
                    string[] str_arr = str.Split(',');

                    for (int i = 0; i < str_arr.Length; i++)
                    {
                        //0表示进厂
                        string[] arr = str_arr[i].Split('|');
                        string Carflag = arr[0];    //0表示车进厂 1表示车出厂
                        string Pier = arr[2].Substring(2, 2);   //码头号
                        string LicensePlate = arr[1];           //车牌号
                        if((int.Parse(Pier) < 16)&& (int.Parse(Pier) > 5))
                        {
                            PierBuf[int.Parse(Pier) - 6] = LicensePlate;
                            if (Carflag == "0")
                            {
                                Modify_LicPlate(uint.Parse(Pier) - 6);     //更新对应码头信息

                                textBox3.AppendText("码位：" + Pier + "  ");
                                textBox3.AppendText("车牌号：" + LicensePlate);
                                textBox3.AppendText("\r\n");
                                WriteLog("车号进出场", "码位：" + Pier + "  " + "车牌号：" + LicensePlate + "\r\n");
                            }
                            else
                            {
                                PierBuf[int.Parse(Pier) - 6] = "暂无车辆";
                                Modify_LicPlate(uint.Parse(Pier) - 6);
                                textBox3.AppendText(Pier.ToString() + "码头车辆出厂");
                                textBox3.AppendText("\r\n");
                                WriteLog("车号进出场", Pier.ToString() + "码头车辆出厂" + "\r\n");
                            }
                            Thread.Sleep(1000);
                        }                      
                    }             
                }
                catch
                {
                    if (MessageShow_NG == true)
                    {
                        WriteLog("errlog", str);
                    }
                }
            }
            //接收到回复的DN号和栈板号
            if (str.StartsWith("OK"))
            {
                string[] arr = null;
                string Pier = null;    //码头
                string LicensePlate = null;    //车牌号
                try
                {
                    str = str.Trim();
                    if (utf8_flag == true)  //重新编码
                    {
                        byte[] strByte = Encoding.Default.GetBytes(str);

                        //需要转成了编码
                        Encoding ecLastCode = Encoding.GetEncoding("utf-8");
                        str = ecLastCode.GetString(strByte);
                    }

                    textBox5.AppendText(str + "\r\n");
                    arr = str.Split(','); // 以','字符对字符串进行分割，返回字符串数组
                    Pier = arr[1].Substring(2, 2);   //码头号
                    LicensePlate = arr[2];
                    
                    for (int i = 0; i < arr.Length - 3; i++)
                    {
                        DN[i] = arr[3 + i].Substring(0, arr[3 + i].IndexOf("|"));
                        Pallet[i] = arr[3 + i].Substring(arr[3 + i].IndexOf("|") + 1, arr[3 + i].Length - arr[3 + i].IndexOf("|") - 1);
                        textBox1.AppendText("码头号" + Pier + " 车牌号：" + LicensePlate + "\r\n");
                        textBox1.AppendText("DN: " + DN[i] + "  " + "栈板号：" + Pallet[i]);
                        textBox1.AppendText("\r\n");
                        WriteLog("DN栈板号", "码头号" + Pier + " 车牌号：" + LicensePlate + "DN: " + DN[i] + "  " + "栈板号：" + Pallet[i] + "\r\n");
                    }                  
                }
                catch
                {
                    if (MessageShow_NG == true)
                    {
                        WriteLog("errlog", str);
                    }
                }
                try
                {
                    Update_Internal_Screen("R", Pier, Pallet, arr.Length - 3);      //修改室内屏幕信息

                    Modify_DN(uint.Parse(Pier) - 6, DN, Pallet, arr.Length - 3);   //修改需要送至的码头屏幕信息       

                    label1.Text = "请送至" + Pier + "号码位";
                }
                catch
                {

                }
                Thread.Sleep(10000);
                if (serialPort1.IsOpen)
                {
                    serialPort1.Write("ready\r\n");
                }
            }
            else if (str.StartsWith("NG"))
            {
                str = str.Trim();
                if (utf8_flag == true)  //重新编码
                {
                    byte[] strByte = Encoding.Default.GetBytes(str);

                    //需要转成了编码
                    Encoding ecLastCode = Encoding.GetEncoding("utf-8");
                    str = ecLastCode.GetString(strByte);
                }

                label1.Text = str.Replace("NG,", "");
                Update_Internal_Screen("R", label1.Text);    //修改室内屏幕信息
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string str = serialPort1.ReadTo("\r\n");

            if (str == "OK")    //接收到下位机OK命令则开始上传信息
            {
                button13.Enabled = true;
                string serialSendStr = "";    //用来拼接扫描枪数据
                try
                {
                    for (int i = 0; i < 6; i++)
                    {
                        if (serial.SerialDataReceived[i] != null)
                        {
                            if (!serialSendStr.Contains(serial.SerialDataReceived[i]))    //确认扫描器没有重复的条码
                            {
                                serialSendStr += serial.SerialDataReceived[i] + ",";
                                textBox4.AppendText(serial.SerialDataReceived[i]);
                                textBox4.AppendText("\r\n");
                                WriteLog("条码", "条码号：" +serial.SerialDataReceived[i] + "\r\n");
                            }
                            serial.SerialDataReceived[i] = null;    //接收完清空
                        }
                    }
                }
                catch
                {
                    if (MessageShow_NG == true)
                        MessageBox.Show("扫描枪数据错误！");
                }
                if (serialSendStr.Contains("MD") || serialSendStr.Contains("ME") || serialSendStr.Contains("PD"))
                {
                    serialPort_Sys.Write(serialSendStr.TrimEnd(','));
                }
            }
            else if (str == "ONOK")
            {
                MessageBox.Show("设备开启成功");
            }
            else if (str == "OFFOK")
            {
                MessageBox.Show("设备关闭成功");
            }
        }

        private void 自定义测试()
        {
            int x = 0;
            m_dwCurHand = Set_data(IP_Buf[5]);    //连接对应屏幕的IP
            ONNONLed5KSDKD.Led5kSDK.SetTimeout(m_dwCurHand, timeout);
            if (m_dwCurHand != 0)   //连接成功
            {
                bx_5k.DynamicAreaLoc = (byte)3;     //动态编号
                Led5K_Set(0, 1, 0, 0, 0, 192, 24, @"\T000T|");   //设置屏幕的参数，起始位置大小，数据
                Led5K_Set(0, 1, 0, 192, 0, 192, 24, @"\T000T|");
                try
                {
                    x = ONNONLed5KSDKD.Led5kSDK.SCREEN_SendDynamicArea(m_dwCurHand, bx_5k, (ushort)bx_5k.DataLen, AreaText);
                }
                catch
                {

                }
                if (x == 0)
                {
                    if (MessageShow_OK == true)
                        MessageBox.Show("动态区域更新成功");
                }
                else
                {
                    if (MessageShow_NG == true)
                        MessageBox.Show("动态区域更新失败");
                }
            }
            else
            {
                WriteLog("errlog", "连接控制器失败");
                if (MessageShow_NG == true)
                    MessageBox.Show("连接控制器失败");
            }

            ONNONLed5KSDKD.Led5kSDK.Destroy(m_dwCurHand);
        }

        private void button14_Click(object sender, EventArgs e)
        {
            serialPort1.Write("back\r\n");
        }

        private void button15_Click(object sender, EventArgs e)
        {
            bx_5k.DisplayMode = 1;  //静止显示

            m_dwCurHand = Set_data(IP_Buf[(uint)numericUpDown1.Value - 6]);    //连接对应屏幕的IP
            ONNONLed5KSDKD.Led5kSDK.SetTimeout(m_dwCurHand, timeout);
            if (m_dwCurHand != 0)   //连接成功
            {
                ONNONLed5KSDKD.Led5kSDK.SCREEN_DelDynamicArea(m_dwCurHand, 255);
            }
            else
            {
                WriteLog("errlog", "连接控制器失败");
                if (MessageShow_NG == true)
                    MessageBox.Show("连接控制器失败");
            }

            ONNONLed5KSDKD.Led5kSDK.Destroy(m_dwCurHand);      
        }

        private void button13_Click_1(object sender, EventArgs e)
        {
            button13.Enabled = false;
            serialPort1.Write("go\r\n");
        }

        bool auto_flag = false;  //默认手动模式
        private void button14_Click_1(object sender, EventArgs e)
        {
            if (button14.Text == "自动模式")
            {
                button14.Text = "手动模式";
                auto_flag = false;
            }
            else
            {
                button14.Text = "自动模式";
                auto_flag = true;
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            password pw = new password();
            pw.ShowDialog();
            if (defaultPWD == pw.pwd)
            {
                panel1.Visible = true;
            }
            else if (pw.pwd == "1234")
            {
                panel2.Visible = true;
            }
            else
            {
                MessageBox.Show("密码错误！");
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Write("on\r\n");
            }
            catch
            {
                MessageBox.Show("串口未开启！");
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            panel1.Visible = false;
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Write("off\r\n");
            }
            catch
            {
                MessageBox.Show("串口未开启！");
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1_time++;
            if (timer1_time == 20)
            {
                timer1_time = 0;
                textBox4.Text = "";
            }
            if (auto_flag == false)
            {
                string serialSendStr = "";    //用来拼接扫描枪数据
                try
                {
                    for (int i = 0; i < 6; i++)
                    {
                        if (serial.SerialDataReceived[i] != null)
                        {
                            if (!textBox4.Text.Contains(serial.SerialDataReceived[i]))
                            {
                                if (!serialSendStr.Contains(serial.SerialDataReceived[i]))    //确认扫描器没有重复的条码
                                {
                                    serialSendStr += serial.SerialDataReceived[i] + ",";
                                    textBox4.AppendText(serial.SerialDataReceived[i]);
                                    textBox4.AppendText("\r\n");
                                }
                                serial.SerialDataReceived[i] = null;    //接收完清空
                            }
                        }
                    }
                }
                catch
                {
                    if (MessageShow_NG == true)
                        MessageBox.Show("扫描枪数据错误！");
                }
                if (serialSendStr.Contains("MD") || serialSendStr.Contains("ME") || serialSendStr.Contains("PD"))
                {
                    serialPort_Sys.Write(serialSendStr.TrimEnd(','));
                }
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            label7.Left = label7.Left - 5;
            if (label7.Right < 300)
            {
                label7.Left = this.Width - 300;
            }
        }

        private void label7_Click(object sender, EventArgs e)
        {
            MessageBox.Show("fsd");
        }

        private void test()
        {
               
                    //str = str.Replace(",999", "");
                    //str = str.Replace("666,", "");
                    //str = str.Trim();
                    //if (utf8_flag == true)  //重新编码
                    //{
                    //    byte[] strByte = Encoding.Default.GetBytes(str);

                    //    //需要转成了编码
                    //    Encoding ecLastCode = Encoding.GetEncoding("utf-8");
                    //    str = ecLastCode.GetString(strByte);
                    //}

                    //textBox5.AppendText(str + "\r\n");
                    //string[] str_arr = str.Split(',');

                    //for (int i = 0; i < str_arr.Length; i++)
                    //{
                    //    //0表示进厂
                    //    string[] arr = str_arr[i].Split('|');
                    //    string Carflag = arr[0];    //0表示车进厂 1表示车出厂
                    //    string Pier = arr[2].Substring(2, 2);   //码头号
                    //    string LicensePlate = arr[1];           //车牌号
                    //    if ((int.Parse(Pier) < 16) && (int.Parse(Pier) > 5))
                    //    {
                    //        PierBuf[int.Parse(Pier) - 6] = LicensePlate;
                    //        if (Carflag == "0")
                    //        {
                    //            Modify_LicPlate(uint.Parse(Pier) - 6);     //更新对应码头信息

                    //            textBox3.AppendText("码位：" + Pier + "  ");
                    //            textBox3.AppendText("车牌号：" + LicensePlate);
                    //            textBox3.AppendText("\r\n");
                    //            WriteLog("车号进出场", "码位：" + Pier + "  " + "车牌号：" + LicensePlate + "\r\n");
                    //        }
                    //        else
                    //        {
                    //            PierBuf[int.Parse(Pier) - 6] = "暂无车辆";
                    //            Modify_LicPlate(uint.Parse(Pier) - 6);
                    //            textBox3.AppendText(Pier.ToString() + "码头车辆出厂");
                    //            textBox3.AppendText("\r\n");
                    //            WriteLog("车号进出场", Pier.ToString() + "码头车辆出厂" + "\r\n");
                    //        }
                    //        Thread.Sleep(1000);
                    //    }
                    //}
                
            
        }

        private void button7_Click(object sender, EventArgs e)
        {
            PierBuf[(uint)numericUpDown2.Value - 6] = textBox2.Text;
            Modify_LicPlate((uint)numericUpDown2.Value - 6);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            panel2.Visible = false;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            button4.Enabled = false;
            for (int i = 0; i < 10; i++)
            {
                PierBuf[i] = "暂无车辆";
                Modify_LicPlate((uint)i);
                Thread.Sleep(500);
            }
            button4.Enabled = true;
            MessageBox.Show("完成");
        }

        private void button11_Click(object sender, EventArgs e)
        {
            PierBuf[(uint)numericUpDown2.Value - 6] = "暂无车辆";
            Modify_LicPlate((uint)numericUpDown2.Value - 6);
        }
    }
}
